<template>
	<div class="yellow">
		<div class="header flex a-center jlr" v-if="!selectaddressState">
			<div class="back" @click="back"><i class="iconfont icon-arrow-left-copy"></i></div>
			<h2>确认订单</h2>
			<div class="back">&nbsp;</div>
		</div>
		<div class="abox" v-if="objstate">
			<div class="order">
				<div class="orderTitle flex a-center" @click="selectaddressState = true">
					<div style="flex: 1;">
						<h2> {{obj.address.contactsName}} <span>{{obj.address.phone}}</span> </h2>
						<div class="address"><span v-if="obj.address.isDefault">默认</span>{{obj.address.dtlAddr}}</div>
					</div>
					<i class="iconfont icon-arrow-right"></i>
				</div>
				<div class="orderpro flex" v-for="(v,i) in obj.productList" :key="v.productId">
					<div class="img"><img :src="v.frontPicUrl"></div>
					<div class="info flex col jlr">
						<div>
							<h2>{{v.productName}}</h2>
							<div class="params">颜色：{{v.colorName}} <span>{{v.specsName}}</span> </div>
						</div>
						<div class="flex jlr">
							<div class="price">￥{{v.price}}</div>
<!-- 							<div class="calc-wrap">
							  <i @click="buyNumsChange(v,'-')" class="iconfont icon-jianhao1"></i>
							  <span class="num">{{v.buyNums}}</span>
							  <i @click="buyNumsChange(v,'+')" class="iconfont icon-jiahao"></i>
							</div> -->
							<van-stepper v-model="v.buyNums" :min="1" async-change @change="onChange($event,i)" />
							<!--v.buyNums-->
						</div>
					</div>
				</div>

				<div class="ordergroup">
					<div class="item flex jlr a-center" @click="paymentShow=true">
						<h4>付款方式</h4>
						<div class="tip" v-if="payType == 2">
							<p>货到付款仅支持河南和河南周边城市</p>邮费到付
						</div>
						<div class="rightgroup flex a-center">
							<span>{{paymentName}}</span>
							<i class="iconfont icon-arrow-right"></i>
						</div>
					</div>

					<div class="item flex jlr a-center" @click="shipShow=true">
						<h4>选择快递</h4>
						<div class="rightgroup flex a-center">
							<span>{{shiName}}</span>
							<i class="iconfont icon-arrow-right"></i>
						</div>
					</div>

					<!--<div class="item flex jlr a-center">-->
					<!--<h4>售后服务</h4>-->
					<!--<div class="rightgroup flex a-center">-->
					<!--<span>七天退款</span>-->
					<!--<i>&nbsp;</i>-->
					<!--</div>-->
					<!--</div>-->
					<div class="item flex jlr a-center">
						<h4>运&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;费</h4>
						<div class="rightgroup flex a-center">
							<span class="ce">+￥{{obj.shipFee}}</span>
							<i>&nbsp;</i>
						</div>
					</div>
				</div>


				<div class="textareabox">
					<h4 v-if="payType==1">支付方式</h4>
					<div class="plabox" v-if="payType==1">
						<van-radio-group v-model="payMode">
							<div class="flex a-center jlr itemgroup" @click="payMode = '1'">
								<div class="item flex a-center">
									<i class="iconfont icon-cashdesk_wx" style="margin-right: 0.1rem; font-size: 0.4rem; color: #41b035;"></i>
									微信支付
								</div>
								<van-radio name="1" checked-color="#fe7537" />
							</div>
							<div class="flex a-center jlr itemgroup" @click="payMode = '2'">
								<div class="item flex a-center">
									<i class="iconfont icon-zhifubao" style="margin-right: 0.1rem; font-size: 0.4rem; color: #1296db;"></i>
									支付宝支付
								</div>
								<van-radio name="2" checked-color="#fe7537" />
							</div>
						</van-radio-group>
					</div>
					<textarea placeholder="备注:需和商家协商好" v-model="remark"></textarea>
				</div>
			</div>

			<div class="orderFixed flex">
				<div class="fx1 flex" style="align-items: flex-end;">合计：<h4>￥<b>{{obj.totalAmt}}</b></h4>
				</div>
				<div class="play" @click="doOrder">{{payType==2?'下单':'支付'}}</div>
			</div>


			<van-actionsheet v-model="paymentShow" :actions="paymentActions" @select="onPaymentSelect" />


			<van-actionsheet v-model="shipShow" :actions="shipActions" @select="onShipSelect" />

			<selectaddress :shows.sync="selectaddressState" v-if="selectaddressState" @cb="cbt"></selectaddress>
		</div>
	</div>
</template>
<script>
	import selectaddress from '../address/main.vue'

	export default {
		name: "orderMain",
		components: {
			selectaddress
		},
		data() {
			return {
				buyNums: 1,
				pays: [],
				obj: {},
				paymentName: '',
				shiName: '',
				selectaddressState: false,
				isPayment: false,
				isShi: false,
				Paymentarr: [],
				shiarr: [],
				objstate: false,
				radio: '1',
				value: 1,
				payType: null,
				payMode: '1',
				shipCompanyId: null,
				remark: null,
				wxChannel: null,
				aliChannel: null,
				paymentShow: false,
				paymentTitle: '支付方式',
				paymentActions: [],
				shipShow: false,
				shipActions: []
			}
		},
		created() {
			console.log('order created from: ', this.$route.query.from);
			this.init();
		},
		mounted() {
			var that = this
			that.onPlusReady(function() {
				plus.payment.getChannels(function(channels) {
					for (var i in channels) {
						var channel = channels[i];
						if (channel.id == 'qhpay' || channel.id == 'qihoo') {
							continue;
						}

						if (channel.id == "wxpay") {
							that.wxChannel = channel;
						} else if (channel.id == "alipay") {
							that.aliChannel = channel;
						}

					}
				}, function(e) {
					outLine('获取支付通道失败：' + e.message);
				});
			})
		},
		methods: {
			onChange(value, index) {
				var that = this
				that.$set(that.obj.productList, index, {
					...that.obj.productList[index],
					buyNums: value
				})
				that.$ajax.getShipFeeTotalAmt({
					area: that.obj.address.area,
					payType: that.payType,
					products: (function(arr) {
						return arr.map(el => {
							return {
								productId: el.productId,
								colorId: el.colorId,
								specsId: el.specsId,
								buyNums: el.buyNums
							}
						})
					})(that.obj.productList)
				}).then(res => {
					if (res.code == 0) {
						that.obj.shipFee = res.data.shipFee
						that.obj.totalAmt = res.data.totalAmt
					}
				})
			},
			cbt(v) {
				console.log(v)
				var that = this
				that.obj.address.addrId = v.addrId;
				that.obj.address.dtlAddr = v.dtlAddr
				that.obj.address.contactsName = v.contactsName
				that.obj.address.phone = v.phone
				that.obj.address.isDefault = v.isDefault
				that.obj.address.area = v.area
				that.$ajax.getShipFeeTotalAmt({
					area: v.area,
					payType: that.PaymentName == '货到付款' ? 2 : 1,
					products: (function(arr) {
						return arr.map(el => {
							return {
								productId: el.productId,
								colorId: el.colorId,
								specsId: el.specsId,
								buyNums: el.buyNums
							}
						})
					})(that.obj.productList)
				}).then(res => {
					if (res.code == 0) {
						that.obj.shipFee = res.data.shipFee
						that.obj.totalAmt = res.data.totalAmt
						that.$ajax.getPayWayShip({
							area: that.obj.address.area
						}).then(res => {
							that.mapPayment(res.data.payWayList)
							that.mapshia(res.data.shipList)
						})
					}
				})
			},
			init() {
				var that = this;
				let from = that.$route.query.from;
				if (from == 'goodsDtl' && that.$route.query.productId) {
					that.$ajax.buyNowProduct({
						productId: that.$route.query.productId,
						colorId: that.$route.query.colorId,
						specsId: that.$route.query.specsId,
						price: that.$route.query.price,
						buyNums: that.$route.query.buyNums
					}).then(res => {
						if (res.code == 0) {
							that.obj = res.data
							that.obj.address.addrId = that.obj.address.addrId

							that.mapPayment(res.data.PaymentList)
							that.mapshia(res.data.shipList)
							that.objstate = true
						}
					})
				} else if (from == 'cart') {
					let ids = JSON.parse(decodeURIComponent(that.$route.query.ids));
					console.log('ids', ids);

					let reqData = {
						shopCarIds: ids
					};
					console.log('shopCarSettle reqData,', reqData);

					that.$ajax.shopCarSettle(reqData).then(res => {
						if (res.code == 0) {
							that.obj = res.data;
							that.mapPayment(res.data.PaymentList)
							that.mapshia(res.data.shipList)
							that.objstate = true
						}
					})
				}
			},
			mapPayment(arr) {
				const that = this;
        that.paymentActions = [];
				if (arr != null && arr.length == 1) {
					this.payType = arr[0].payType;
					this.paymentName = arr[0].name;
				}
				if(arr){
          arr.forEach(function(item, index, array) {
            const obj = {
              code: item.payType,
              name: item.name
            };
            that.paymentActions.push(obj);
          });
        }
			},
			onPaymentSelect(item) {
				var that = this
				that.payType = item.code;
				that.paymentName = item.name;
				that.$ajax.getShipFeeTotalAmt({
					area: that.obj.address.area,
					payType: item.code,
					products: (function(arr) {
						return arr.map(el => {
							return {
								productId: el.productId,
								colorId: el.colorId,
								specsId: el.specsId,
								buyNums: el.buyNums
							}
						})
					})(that.obj.productList)
				}).then(res => {
					if (res.code == 0) {
						that.obj.shipFee = res.data.shipFee
						that.obj.totalAmt = res.data.totalAmt
					}
				})
				that.paymentShow = false;
			},
			mapshia(arr) {
				const that = this;
        that.shipActions = [];
        if(arr){
          arr.forEach(function(item, index, array) {
            const obj = {
              code: item.shipId,
              name: item.shipName
            };
            that.shipActions.push(obj);
          });
        }
			},
			onShipSelect(item) {
				this.shipCompanyId = item.code;
				this.shiName = item.name;
				this.shipShow = false;
			},
			back() {
				this.$router.go(-1)
			},
			doOrder() {
				let that = this;
				console.log(that.obj.address.addrId)

        if(!that.obj.address.addrId){
          that.$toast('请选择地址');
          return false;
        }

				if (!that.payType) {
					that.$toast('请选择付款方式');
					return false;
				}

				if (!that.shipCompanyId) {
					that.$toast('请选择快递');
					return false;
				}

				let reqData = {
					products: this.obj.productList,
					totalAmt: this.obj.totalAmt,
					shipFee: this.obj.shipFee,
					payType: this.payType,
					payMode: this.payMode,
					addrId: this.obj.address.addrId,
					shipCompanyId: this.shipCompanyId,
					remark: this.remark
				};

				this.$ajax.confirmOrder(reqData).then(res => {
          let payChl = this.payMode == '1' ? this.wxChannel : this.aliChannel;
          let data = res.data;
          if (res.code == 0 && that.payType == 1) {
						if (data) {
							plus.payment.request(payChl, data.payParams, function(result) {
								that.$toast.success('支付成功');
								let query = {
								  orderId: data.orderId,
                  payStatus: 1,
                  payType: that.payType
                };
								this.goPayResult(query);
							}, function(e) {
								that.$toast.fail('支付失败');
                let query = {
                  orderId: data.orderId,
                  payStatus: 0,
                  payType: that.payType
                };
                this.goPayResult(query);
							});
						}else{
              that.$toast.fail('下单失败');
            }
					} else if (res.code == 0 && that.payType == 2) {
            let query = {
              orderId: data.orderId,
              payStatus: 1,
              payType: that.payType
            };
            this.goPayResult(query);
					}
				})
			},
      goPayResult(query){
        let toPath = {
          path: '/orderstaus',
          query: query
        };
        this.$router.replace(toPath);
      }
		}
	}
</script>
